package com.flyco.modules.returns.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.modules.oms.entity.OmsOrder;
import com.flyco.modules.oms.entity.OmsOrderItem;
import com.flyco.modules.oms.entity.OmsOrderSetting;
import com.flyco.modules.oms.entity.OmsOrderTrace;
import com.flyco.modules.oms.service.IOmsOrderItemService;
import com.flyco.modules.oms.service.IOmsOrderService;
import com.flyco.modules.oms.service.IOmsOrderSettingService;
import com.flyco.modules.oms.service.IOmsOrderTraceService;
import com.flyco.modules.oms.vo.OmsSendOrderDto;
import com.flyco.modules.oms.vo.OmsSendOrderItem;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.returns.entity.*;
import com.flyco.modules.returns.mapper.OmsOrderReturnApplyMapper;
import com.flyco.modules.returns.service.IOmsOrderReturnApplyService;
import com.flyco.modules.returns.service.IOmsOrderReturnItemBatchService;
import com.flyco.modules.returns.service.IOmsOrderReturnItemService;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.stm.service.IStmStoreProductStockService;
import com.flyco.modules.ums.model.UmsMemberReceiveAddressModel;
import com.flyco.modules.ums.service.IUmsMemberReceiveAddress;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 申请退换货
 * @Author: flyco
 * @Date: 2023-08-01
 * @Version: V1.0
 */
@Service
public class OmsOrderReturnApplyServiceImpl extends ServiceImpl<OmsOrderReturnApplyMapper, OmsOrderReturnApply> implements IOmsOrderReturnApplyService {

    @Autowired
    private OmsOrderReturnApplyMapper applyMapper;
    @Autowired
    private IOmsOrderSettingService omsOrderSettingService;
    @Autowired
    private IOmsOrderService orderService;
    @Autowired
    private IOmsOrderItemService orderItemService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private IOmsOrderTraceService omsOrderTraceService;
    @Autowired
    private IOmsOrderReturnItemService returnItemService;
    @Autowired
    private IOmsOrderReturnItemBatchService returnItemBatchService;
    @Autowired
    private IStmStoreInfoService storeInfoService;
    @Autowired
    private IUmsMemberReceiveAddress memberReceiveAddress;
    @Autowired
    private IOmsOrderService omsOrderService;
    @Autowired
    private IStmStoreProductStockService productStockService;


    /**
     * 获取门店3个月内购买的商品列表，供退货时进行选择
     */
    @Override
    public List<PmsProduct> getOrderReturnProductList(Long storeId, String productName) {

        LocalDateTime beginTime;
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        if (orderSetting == null || orderSetting.getReturnsOvertime() == null) {
            beginTime = LocalDateTime.now().minusMonths(3);
        } else {
            beginTime = LocalDateTime.now().minusDays(orderSetting.getReturnsOvertime());
        }

        StmStoreInfo storeInfo = stmStoreInfoService.getById(storeId);

        //查询配置的时间段内的订单id
        List<OmsOrder> orderList = orderService.getOrderList(storeInfo.getStoreId(), beginTime);

        if (CollectionUtils.isEmpty(orderList)) {
            return null;
        }

        List<String> orderIdList = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());

        List<OmsOrderItem> orderItemList = orderItemService.getOrderItemByIds(orderIdList, productName);

        if (CollectionUtils.isEmpty(orderItemList)) {
            return null;
        }

        List<PmsProduct> productList = orderItemList.stream().map(item -> {
            PmsProduct pmsProduct = new PmsProduct();
            pmsProduct.setName(item.getProductName());
            pmsProduct.setSkuCode(item.getProductSkuCode());
            pmsProduct.setId(item.getProductId());
            return pmsProduct;
        }).collect(Collectors.toList());

        return productList.stream().distinct().collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Result<?> logisticsApprove(OrderReturnApproveDTO returnApproveDTO) {

        List<OmsOrderReturnItem> returnItemList = returnItemService.getByApplyId(returnApproveDTO.getId());

        //更新批次表
        List<OmsOrderReturnItemBatch> itemBatchList = returnItemBatchService.getByApplyId(returnApproveDTO.getId());
        Map<Long, OmsOrderReturnItemBatch> itemBatchMap = itemBatchList.stream()
                .collect(Collectors.toMap(OmsOrderReturnItemBatch::getId, a -> a));
        List<OmsOrderReturnItemBatch> needUpdateBatch = new ArrayList<>();
        if (!CollectionUtils.isEmpty(returnApproveDTO.getItemList())) {
            returnApproveDTO.getItemList().forEach(item -> {
                OmsOrderReturnItemBatch returnItemBatch = itemBatchMap.get(item.getId());
                returnItemBatch.setRealUnitQuantity(item.getReturnSkuUnitCountNotUnit() * returnItemBatch.getProductSkuSpec() + item.getReturnUnitCountNotUnit());
                needUpdateBatch.add(returnItemBatch);
            });
        }
        returnItemBatchService.updateBatchById(needUpdateBatch);

        //审批通过后，创建发货单，OmsSendOrderDto对象的属性都要设置值
        OmsOrderReturnApply returnApplyInfo = getById(returnApproveDTO.getId());
        if (!returnApplyInfo.getStatus().equals(3)) {
            return Result.error("数据已过期!");
        }
        returnApplyInfo.setStatus(returnApproveDTO.getStatus());
        returnApplyInfo.setApproveComments(returnApproveDTO.getApproveComments());
        updateById(returnApplyInfo);


        //根据批次表再更新退单明细表
        Map<Long, OmsOrderReturnItem> itemMap = returnItemList.stream()
                .collect(Collectors.toMap(OmsOrderReturnItem::getId, a -> a));
        List<OmsOrderReturnItem> needUpdate = new ArrayList<>();
        if (!CollectionUtils.isEmpty(returnApproveDTO.getItemList())) {

            List<OrderReturnItemDTO> returnItemDTOList = returnApproveDTO.getItemList();
            Map<Long, List<OrderReturnItemDTO>> itemDTOByProductIdMap = returnItemDTOList.stream()
                    .collect(Collectors.groupingBy(OrderReturnItemDTO::getProductId));

            for (OmsOrderReturnItem item : returnItemList) {
                OmsOrderReturnItem omsOrderReturnItem = itemMap.get(item.getId());
                List<OrderReturnItemDTO> itemByProduct = itemDTOByProductIdMap.get(item.getProductId());
                Integer skuUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getReturnSkuUnitCountNotUnit).sum();
                Integer unitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getReturnUnitCountNotUnit).sum();

                item.setRealUnitQuantity(skuUnitCount * omsOrderReturnItem.getProductSkuSpec() + unitCount);
                needUpdate.add(item);
            }
        }
        returnItemService.updateBatchById(needUpdate);

        saveOrderTrace(returnApproveDTO, returnApplyInfo.getStatus(), returnApplyInfo.getReturnType());

        return Result.ok("审批完成");
    }

    /**
     * 改功能是跟单员审核，为兼容代替销售审核，所以根据状态来判断是销售审核还是跟单员进行审核
     */
    private Result saveOrderTrace(OrderReturnApproveDTO omsOrderReturnApply, Integer oldStatus, Integer returnType) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(omsOrderReturnApply.getId().toString());
        omsOrderTrace.setCreateTime(new Date());
        omsOrderTrace.setCreateBy(sysUser.getRealname());
        if (omsOrderReturnApply.getStatus().equals(6)) {
            omsOrderTrace.setLabel("物流审核通过，请在退单详情[物流实收]中查看如有疑问可联系工作人员");
            omsOrderTrace.setContent("");
        } else if (omsOrderReturnApply.getStatus().equals(5)) {
            omsOrderTrace.setLabel("跟单员审核通过");
            omsOrderTrace.setContent("");
        } else if (omsOrderReturnApply.getStatus().equals(7)) {
            omsOrderTrace.setLabel("品检确认，请在退单详情[品检检测]中查看，如有疑问可联系工作人员");
            omsOrderTrace.setContent("");
        } else if (omsOrderReturnApply.getStatus().equals(8)) {
            omsOrderTrace.setLabel("财务确认");
            omsOrderTrace.setContent("");
        } else if (omsOrderReturnApply.getStatus() == 4 && oldStatus.equals(3) && Objects.equals(returnType, 1)) {
            omsOrderTrace.setLabel("物流审核不通过：" + omsOrderReturnApply.getApproveComments());
            omsOrderTrace.setContent(omsOrderReturnApply.getApproveComments());
        } else if (omsOrderReturnApply.getStatus() == 4 && oldStatus.equals(6)) {
            omsOrderTrace.setLabel("品检确认，请在退单详情[品检检测]中查看，如有疑问可联系工作人员");
            omsOrderTrace.setContent("");
        } else if (omsOrderReturnApply.getStatus() == 4 && oldStatus.equals(7)) {
            omsOrderTrace.setLabel("跟单员审核不通过：" + omsOrderReturnApply.getApproveComments());
            omsOrderTrace.setContent(omsOrderReturnApply.getApproveComments());
        } else if (omsOrderReturnApply.getStatus() == 4 && oldStatus.equals(3) && Objects.equals(returnType, 3)) {
            omsOrderTrace.setLabel("财务审核不通过：" + omsOrderReturnApply.getApproveComments());
            omsOrderTrace.setContent(omsOrderReturnApply.getApproveComments());
        }
        omsOrderTraceService.save(omsOrderTrace);

        return Result.ok("成功!");
    }


    @Override
    @Transactional
    public Result<?> inspectionApprove(OrderReturnApproveDTO returnApproveDTO) {
        //获取该申请带有批次号的明细列表，并按照id进行map
        List<OmsOrderReturnItemBatch> itemBatchList = returnItemBatchService.getByApplyId(returnApproveDTO.getId());
        Map<Long, OmsOrderReturnItemBatch> itemBatchMap = itemBatchList.stream()
                .collect(Collectors.toMap(OmsOrderReturnItemBatch::getId, a -> a));


        //验证用户输入的报废+返仓+不通过的数量是否等于实收数量，如果不相等，不让审核通过
        List<OmsOrderReturnItemBatch> needUpdateBatch = new ArrayList<>();

        if (!CollectionUtils.isEmpty(returnApproveDTO.getItemList())) {
            for (OrderReturnItemDTO item : returnApproveDTO.getItemList()) {
                OmsOrderReturnItemBatch omsOrderReturnItem = itemBatchMap.get(item.getId());
                //拒绝售后的货品数量（按瓶）
                omsOrderReturnItem.setRefuseUnitQuantity(item.getRefuseSkuUnitQuantity() * omsOrderReturnItem.getProductSkuSpec() + item.getRefuseUnitQuantity());
                //报废的货品数量（按瓶）
                omsOrderReturnItem.setUselessUnitQuantity(item.getUselessSkuUnitQuantity() * omsOrderReturnItem.getProductSkuSpec() + item.getUselessUnitQuantity());
                //可再次利用的货品数量（按瓶）返仓
                omsOrderReturnItem.setReuseUnitQuantity(item.getReuseSkuUnitQuantity() * omsOrderReturnItem.getProductSkuSpec() + item.getReuseUnitQuantity());

                Integer count = omsOrderReturnItem.getRefuseUnitQuantity() + omsOrderReturnItem.getUselessUnitQuantity() + omsOrderReturnItem.getReuseUnitQuantity();
                if (!omsOrderReturnItem.getRealUnitQuantity().equals(count)) {
                    //如果跟物流实收数量不相等，则终止后面的操作，提示用户重新填写。
                    return Result.error(omsOrderReturnItem.getProductName() + "商品跟实收数量不等，请重新输入！");
                }

                //小计金额(报废+返仓)
                BigDecimal totalAmount = BigDecimal.valueOf(omsOrderReturnItem.getUselessUnitQuantity() + omsOrderReturnItem.getReuseUnitQuantity()).multiply(omsOrderReturnItem.getPrice());
                omsOrderReturnItem.setTotalRealAmount(totalAmount);

                needUpdateBatch.add(omsOrderReturnItem);
            }
        }
        returnItemBatchService.updateBatchById(needUpdateBatch);


        //审批通过后，创建发货单，OmsSendOrderDto对象的属性都要设置值
        OmsOrderReturnApply returnApplyInfo = getById(returnApproveDTO.getId());
        if (!returnApplyInfo.getStatus().equals(6)) {
            return Result.error("数据已过期!");
        }
        returnApplyInfo.setStatus(returnApproveDTO.getStatus());
        returnApplyInfo.setApproveComments(returnApproveDTO.getApproveComments());
        returnApplyInfo.setInspectionReport(returnApproveDTO.getInspectionReport());
        updateById(returnApplyInfo);


        //根据批次表再更新退单明细表
        List<OmsOrderReturnItem> returnItemList = returnItemService.getByApplyId(returnApproveDTO.getId());
        Map<Long, OmsOrderReturnItem> itemMap = returnItemList.stream()
                .collect(Collectors.toMap(OmsOrderReturnItem::getId, a -> a));
        List<OmsOrderReturnItem> needUpdate = new ArrayList<>();
        if (!CollectionUtils.isEmpty(returnApproveDTO.getItemList())) {

            List<OrderReturnItemDTO> returnItemDTOList = returnApproveDTO.getItemList();
            Map<Long, List<OrderReturnItemDTO>> itemDTOByProductIdMap = returnItemDTOList.stream()
                    .collect(Collectors.groupingBy(OrderReturnItemDTO::getProductId));

            for (OmsOrderReturnItem item : returnItemList) {
                OmsOrderReturnItem omsOrderReturnItem = itemMap.get(item.getId());
                List<OrderReturnItemDTO> itemByProduct = itemDTOByProductIdMap.get(item.getProductId());
                //拒绝售后的货品数量（瓶的总数）
                Integer refuseUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getRefuseUnitQuantity).sum();
                //拒绝售后的货品数量（箱的总数）
                Integer refuseSkuUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getRefuseSkuUnitQuantity).sum();


                //可再次利用的货品数量（瓶的总数）
                Integer reuseUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getReuseUnitQuantity).sum();
                //可再次利用的货品数量（箱的总数）
                Integer reuseSkuUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getReuseSkuUnitQuantity).sum();

                //报废的货品数量（瓶的总数）
                Integer uselessUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getUselessUnitQuantity).sum();
                //报废的货品数量（箱的总数）
                Integer uselessSkuUnitCount = itemByProduct.stream().mapToInt(OrderReturnItemDTO::getUselessSkuUnitQuantity).sum();


                item.setRefuseUnitQuantity(refuseSkuUnitCount * item.getProductSkuSpec() + refuseUnitCount);
                item.setUselessUnitQuantity(uselessSkuUnitCount * item.getProductSkuSpec() + uselessUnitCount);
                item.setReuseUnitQuantity(reuseSkuUnitCount * item.getProductSkuSpec() + reuseUnitCount);

                //小计金额(报废+返仓)
                BigDecimal totalAmount = BigDecimal.valueOf(item.getUselessUnitQuantity() + item.getReuseUnitQuantity()).multiply(item.getPrice());
                item.setTotalRealAmount(totalAmount);
                needUpdate.add(item);
            }
        }
        returnItemService.updateBatchById(needUpdate);

        saveOrderTrace(returnApproveDTO, returnApplyInfo.getStatus(), returnApplyInfo.getReturnType());

        return Result.ok("审批完成");
    }

    @Override
    @Transactional
    public Result<?> orderManagerApprove(OrderReturnApproveDTO returnApproveDTO) {

        //审批通过后，创建发货单，OmsSendOrderDto对象的属性都要设置值
        OmsOrderReturnApply returnApplyInfo = getById(returnApproveDTO.getId());
        if (!returnApplyInfo.getStatus().equals(7)) {
            return Result.error("数据已过期!");
        }
        returnApplyInfo.setStatus(returnApproveDTO.getStatus());
        returnApplyInfo.setUpdateTime(new Date());
        returnApplyInfo.setApproveComments(returnApproveDTO.getApproveComments());
        updateById(returnApplyInfo);

        saveOrderTrace(returnApproveDTO, returnApplyInfo.getStatus(), returnApplyInfo.getReturnType());

        //退货审核通过后，扣除库存
        List<OmsOrderReturnItem> itemList = returnItemService.getByApplyId(returnApproveDTO.getId());
        for (OmsOrderReturnItem item : itemList) {

            Integer count = (item.getRealUnitQuantity() - item.getRefuseUnitQuantity()) / item.getProductSkuSpec();
            productStockService.updateStock(Long.valueOf(returnApplyInfo.getStoreId()), item.getProductId(), -count);
        }
        return Result.ok("审批完成");
    }

    @Override
    @Transactional
    public Result<?> financeApprove(OrderReturnApproveDTO returnApproveDTO) {
        //审批通过后，创建发货单，OmsSendOrderDto对象的属性都要设置值
        OmsOrderReturnApply returnApplyInfo = getById(returnApproveDTO.getId());
        if (!returnApplyInfo.getStatus().equals(8)) {
            return Result.error("数据已过期!");
        }
        returnApplyInfo.setStatus(returnApproveDTO.getStatus());
        returnApplyInfo.setApproveComments(returnApproveDTO.getApproveComments());
        returnApplyInfo.setUpdateTime(new Date());
        updateById(returnApplyInfo);

        saveReturnOrderFinanceApproveTrace(returnApproveDTO, 8, returnApplyInfo.getReturnType());
        if (returnApplyInfo.getReturnType().equals(3) && returnApproveDTO.getStatus().equals(5)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            OmsSendOrderDto omsSendOrderDto = new OmsSendOrderDto();
            omsSendOrderInit(omsSendOrderDto, returnApproveDTO);
            omsOrderService.addSendOrder(omsSendOrderDto, sysUser, returnApproveDTO.getId());
        }

        //退货审核通过后，扣除库存
        if ((returnApplyInfo.getReturnType().equals(1) || returnApplyInfo.getReturnType().equals(4)) && returnApproveDTO.getStatus().equals(5)) {
            //退货货退款的，认为商品已不能使用，扣除库存
            List<OrderReturnItemDTO> itemList = returnApproveDTO.getItemList();
            for (OrderReturnItemDTO item : itemList) {

                Integer count = item.getRealReturnUnitCount() - item.getRefuseSkuUnitQuantity();
                productStockService.updateStock(Long.valueOf(returnApplyInfo.getStoreId()), item.getProductId(), -count);
            }
        }

        return Result.ok("审批完成！");
    }

    private Result saveReturnOrderFinanceApproveTrace(OrderReturnApproveDTO omsOrderReturnApply, Integer oldStatus, Integer returnType) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(omsOrderReturnApply.getId().toString());
        omsOrderTrace.setCreateTime(new Date());
        omsOrderTrace.setCreateBy(sysUser.getRealname());

        if (omsOrderReturnApply.getStatus().equals(5)) {
            omsOrderTrace.setLabel("财务确认");
            omsOrderTrace.setContent("");

        } else {
            omsOrderTrace.setLabel("财务审核不通过：" + omsOrderReturnApply.getApproveComments());
            omsOrderTrace.setContent(omsOrderReturnApply.getApproveComments());
        }
        omsOrderTraceService.save(omsOrderTrace);

        return Result.ok("成功!");
    }

    /**
     * OmsSendOrderDto 赋值
     */
    private void omsSendOrderInit(OmsSendOrderDto omsSendOrderDto, OrderReturnApproveDTO omsOrderReturnApply) {

        OmsOrderReturnApply returnApply = getById(omsOrderReturnApply.getId());
        StmStoreInfo storeInfo = storeInfoService.getById(returnApply.getStoreId());
        UmsMemberReceiveAddressModel addressInfo = memberReceiveAddress.getDefaultAddressByMemberId(storeInfo.getStoreId());
        List<OmsOrderReturnItem> returnItemList = returnItemService.getByApplyId(returnApply.getId());

        omsSendOrderDto.setNote(returnApply.getReason());
        omsSendOrderDto.setChannelId(Integer.valueOf(storeInfo.getChannelId()));
        omsSendOrderDto.setStoreId(storeInfo.getStoreId());
        omsSendOrderDto.setCompanyAddressId(addressInfo.getId());
        omsSendOrderDto.setOmsOrderItemList(returnItemList.stream().map(o -> {
            OmsSendOrderItem item = new OmsSendOrderItem();
            item.setProductId(o.getProductId());
            item.setProductPrice(o.getPrice());
            item.setBoxPrice(o.getBoxPrice());
            item.setRealAmount(o.getPrice());
            item.setMinUnitQuantity(o.getMinUnitQuantity());
            item.setTotalAmount(o.getTotalAmount());
            item.setProductQuantity(o.getMinUnitQuantity() / o.getProductSkuSpec());
            return item;
        }).collect(Collectors.toList()));
    }

    @Override
    public Result<?> returnPreApprove(OrderReturnApproveDTO returnApproveDTO) {
        OmsOrderReturnApply returnApply = getById(returnApproveDTO.getId());

        if (returnApply.getStatus().equals(7) && returnApproveDTO.getStatus().equals(6)) {
            returnApply.setStatus(6);
        } else if (returnApply.getStatus().equals(6) && returnApproveDTO.getStatus().equals(3)) {
            returnApply.setStatus(3);
        } else {
            return Result.error("信息已变更，请刷新后再试!");
        }
        updateById(returnApply);
        return Result.ok("修改成功");
    }


}
